<template>
  <div style="display:inline">
    <el-tooltip placement="top"
                :content="$t('processDialog.submit')"
                v-if="permission.start">
      <el-button :size="size"
                 :type="buttonType"
                 class="iconfont iconcloud-upload"
                 :loading="startLoading"
                 @click="startProcess"></el-button>
    </el-tooltip>
    <el-tooltip placement="top"
                :content="$t('processDialog.audit')"
                v-if="permission.examine">
      <el-button :size="size"
                 :type="buttonType"
                 class="iconfont iconzu"
                 @click="examine"></el-button>
    </el-tooltip>
    <el-tooltip placement="top"
                :content="$t('processDialog.cancelSubmit')"
                v-if="permission.unExamine">
      <el-button :size="size"
                 :type="buttonType"
                 class="iconfont iconzu3"
                 @click="unExamine"></el-button>
    </el-tooltip>
    <startProcess ref="startProcess"
                  :tableName="tableName"
                  :funcTypeId="funcTypeId"
                  :objectId="objectId"
                  :reloadFunc="reloadFunc"
                  :routePrefix="routePrefix"
                  :isShow="false"
                  @success="getPermission"></startProcess>
    <examine ref="examine"
             :tableName="tableName"
             :funcTypeId="funcTypeId"
             :reloadFunc="reloadFunc"
             :objectId="objectId"
             :params="params"
             :warpId="warpId"
             :routePrefix="routePrefix"></examine>
  </div>
</template>

<script>
import startProcess from './startProcess'
import examine from './examine'
import { getTaskTodo, cancelSubmit, getWfRequireAudit, AddWfSubmit, getFlowTask, getCurrentInstance } from '../../api/processManagement'
import { mapGetters } from 'vuex'

/**
 * 参数说明
 * size --> 按钮尺寸  默认最大
 * permission --> 按钮权限(start:提交按钮权限，examine：审核按钮权限,unExamine:取消提交按钮) 值为true/false
 * tableName --> 数据库表名
 * funcTypeId --> 业务资源实体的类型id
 * objectId --> 审批对象id
 * reloadFunc --> 刷新页面方法
 */
export default {
  components: { startProcess, examine },
  props: {
    size: {
      type: String,
      default: '',
      remark: '按钮尺寸 ',
      values: ''
    },
    permission: {
      type: Object,
      remark: '按钮权限(start:提交按钮权限，examine：审核按钮权限,unExamine:取消提交按钮)',
      default () {
        return { start: false, examine: false, unExamine: false }
      }
    },
    visibleFunc: {
      type: Object,
      remark: '自定义弹窗启用方法',
      default () {
        return {
          start () {
            return new Promise((resolve, reject) => {
              resolve(true)
            })
          },
          examine () {
            return new Promise((resolve, reject) => {
              resolve(true)
            })
          }
        }
      }
    },
    reloadFunc: {
      type: Function,
      remark: '自定义刷新方法',
      default () {
        location.reload()
      }
    },
    buttonType: {
      type: String,
      remark: '按钮类型',
      default: '',
      values: '同element'
    },
    tableName: {
      type: String,
      remark: '数据库表名（业务资源实体可以查到）'
    },
    funcTypeId: {
      type: [Number, String],
      remark: '类型ID、对接状态类型组件后自动写入',
      default: ''
    },
    objectId: {
      remark: '单据ID、必传',
      type: [Number,String]
    },
    routePrefix: {
      remark: '当前模块标识（自动获取、对接跨端组件需要传入）',
      type: String,
      default: ''
    },
    warpId: {
      type: String,
      remark: '审核组件弹窗插入dom位置（传入DOM的下方）',
      default: 'sone-container-warp'
    },
    demo: {
      type: Boolean,
      remark: '接口无法访问时、是否使用demo数据',
      default: false
    }
  },
  data () {
    return {
      params: {},
      startLoading:false
    }
  },
  computed: mapGetters(['currentModule', 'typeId']),
  watch: {
    objectId: {
      handler: 'getPermission'
    }
  },
  mounted(){
    this.getPermission()
  },
  methods: {
    getPermission () {
      getWfRequireAudit(this.tableName, this.funcTypeId || this.typeId).then(res => {
        if (res.data.data === 1)
          getTaskTodo(this.tableName, this.objectId).then(res => {
            if (!res.data.data) this.permission.examine = false
          })
        else this.permission.examine = false
      })
      getFlowTask(this.objectId, this.tableName).then(res => {
        if (Array.isArray(res.data.data) && res.data.data[0].instanceId) {
          getCurrentInstance(res.data.data[0].instanceId).then(res => {
            if (!res.data.data || res.data.data.createBy !== this.$store.getters.userInfo.userId) this.permission.unExamine = false
          })
        }
      })
    },
    startProcess () {
      if (this.demo) this.$refs.startProcess.visible = true
      else {
        this.startLoading=true
        getWfRequireAudit(this.tableName, this.funcTypeId || this.typeId).then(res => {
          this.startLoading=false
          if (res.data.data === 1) this.visibleFunc.start().then(res => {
            if (res) this.$refs.startProcess.visible = true
            else console.error('自定义启动弹窗方法返回值为false')
          })
          else AddWfSubmit(this.routePrefix || this.currentModule.routePrefix, this.tableName, this.objectId).then(res => {
            this.startLoading=false
            this.$message({
              type: res.data.meta.success ? 'success' : 'error',
              message: res.data.meta.message
            })
            this.reloadFunc()
          }).catch(err => {
            this.startLoading=false
            this.reloadFunc()
          })
        })
      }
    },
    examine () {
      if (this.demo) this.$refs.examine.visible = true
      else getTaskTodo(this.tableName, this.objectId).then(res => {
        if (res.data.data) {
          this.params = res.data.data
          this.visibleFunc.examine().then(res => {
            if (res) this.$refs.examine.visible = true
            else console.error('自定义启动弹窗方法返回值为false')
          })
        }
        else this.$message.warning(this.$t('processDialog.noAuth'))
      })
    },
    unExamine () {
      cancelSubmit(this.routePrefix || this.currentModule.routePrefix, this.objectId, this.tableName).then(res => {
        this.$message({
          type: res.data.meta.success ? 'success' : 'error',
          message: res.data.meta.message
        })
        if (res.data.meta.success) {
          this.reloadFunc()
          this.$refs.examine.visible = false
          this.$store.commit("SET_RELOADAUDITINFOMATION", true)
        }
      }).catch((err) => {
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
